package com.interactive.internal.ant;

import java.util.ArrayList;
import java.util.Stack;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.Jar;
import org.apache.tools.ant.types.DataType;

/**
 * JarSet data type for custom ant task that will generate
 * a set of jar files.
 *
 * <p>Title: Ant Batch Jar</p>
 *
 * <p>Copyright: Copyright (c) 2005</p>
 *
 * <p>Company: Interactive Network Technologies Inc.</p>
 *
 * @author John Januskey (john@int.com)
 * @version 1.0
 */
public class JarSet
    extends DataType
{
  private ArrayList jars = new ArrayList();

  /**
   * Adds the specified JarSetElement to the JarSet.
   *
   * @param jarSetElement JarSetElement
   */
  public void addJar(Jar jar)
  {
    if (isReference())
    {
      getRef().addJar(jar);
    }
    else
    {
      jars.add(jar);
    }
  }

  /**
   * returns a list of JarSetElements.
   *
   * @return ArrayList
   */
  public ArrayList getJarSetElementsList()
  {
    ArrayList result = jars;
    if (isReference())
    {
      result = getRef().getJarSetElementsList();
    }
    return result;
  }

  /**
   * Returns the JarSet refered to by the reference id.
   *
   * @return JarSet
   */
  private JarSet getRef()
  {
    if (!isChecked())
    {
      Stack stk = new Stack();
      stk.push(this);
      dieOnCircularReference(stk, getProject());
    }
    Object o = getRefid().getReferencedObject(getProject());

    if (!getClass().isAssignableFrom(o.getClass()))
    {
      throw new BuildException(getRefid().getRefId()
                               + " doesn\'t denote a " + getClass().toString());
    }
    return (JarSet) o;
  }

  /**
   * Adds a new JarSetElement to the JarSet and returns a reference to the new
   * JarSetElement.
   *
   * @return JarSetElement
   */
  public Jar createJar()
  {
    if (isReference())
    {
      throw noChildrenAllowed();
    }

    Jar jar = new Jar();
    jars.add(jar);
    return jar;
  }
}
